<template>
  <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
    <a-form :form="form">
       <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="导入EXCEL"
          hasFeedback> 
            <a-upload 
            name="file"
            accept=".xls,.xlsx"
            :fileList="fileList"
            :remove="handleRemove"
            :beforeUpload="beforeUpload">
                <a-button>
                    <a-icon type="upload" />
                    选择导入文件
                </a-button>
            </a-upload>
        </a-form-item>
      <a-form-item
        :wrapperCol="{ span: 24 }"
        style="text-align: center"
      >
        <a-button @click="handleSubmit" style="margin-left: 8px; display: none;">开始导入</a-button>
      </a-form-item>
    </a-form>
    <a-table
      rowKey="id"
      bordered
      :columns="columns"
      :dataSource="dataSource"
      :pagination="false"
    >
    </a-table>
    <a-modal title="选择需导入数据" destroyOnClose :visible="visibleCreateModal" @ok="handleCreateModalOk" @cancel="handleCreateModalCancel">
      <a-form style="margin-top: 8px">
        <a-form-item :labelCol="{ span: 5 }" :wrapperCol="{ span: 15 }" label="选择表">
            <a-select placeholder="选择表" :value="sheetNum" @change="handleInput">
             <a-select-option
                v-for="(item,index) in sheetOptions"
                :key="index"
                :value="item.index">
                <span style="display: inline-block;width: 100%" :title=" item.name ">
                  {{ item.name }}
                </span>
              </a-select-option>
            </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
function getBase64 (img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
  import { postAction, getAction } from '@/api/manage'
  export default {
    name: 'BaseForm',
    data () {
      return {
        description: '调用百度进行文字识别测试场-增值税发票。',
        value: 1,
        visible:false,
        uploading:false,
        fileList:[],
        uploadAction:window._CONFIG['domianURL']+"/ocr/identify/upload",
        getAction:window._CONFIG['domianURL']+"/ocr/identify/getexcelcount",
        saveAction:window._CONFIG['domianURL']+"/ocr/identify/getexcel",
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        filePath: "",
        visibleCreateModal:false,
        sheetNum: 0,
        sheetOptions: [],
        headers: {},
        previewVisible: false,
        // form
        form: this.$form.createForm(this),
        columns: [ ],
        dataSource: [ ]
      }
    },
    methods: {
      handleClose(){
        this.visible=false
      },
      show(){
        this.fileList = []
        this.uploading = false
        this.visible = true
      },
      handleRemove(file) {
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList
      },
      beforeUpload(file) {
        if(this.fileList.length > 0) {
              this.$message.warning("请删除已选文件");
            return false;
        }
        this.fileList = [...this.fileList, file];
        var that = this;
        const { fileList } = this;
        const formData = new FormData();
        fileList.forEach((file) => {
          formData.append('file', file);
        });
        this.uploading = true;
        postAction(this.uploadAction, formData).then((res) => {
            if (res.success) {
                that.fileName = res.message;
                that.$message.success(res.message);
                that.handleSubmit();
                that.$emit('ok');
            } else {
                that.$message.warning(res.message);
            }
        }).finally(() => {
        })
        return false;
      },
      handleInput(e) { 
        let val = e; 
        this.sheetNum = val;
      },
      //添加逻辑
      handleModalVisible(isVisible) {
        this.visibleCreateModal = isVisible;
      },
      handleCreateModalOk() {
        this.saveUploadInfo();
      },
      handleCreateModalCancel() {
        this.visibleCreateModal = false;
      },
      // handler
      handleSubmit () { 
        var that = this;
        let formData = {};
        formData.dbpath = this.fileName
        this.uploading = true;
        console.log(formData);
        postAction(this.getAction, formData).then((res) => {
            if (res.success) {
                if(res.code == 2) {
                    console.log(res.message);
                    that.$message.success(res.message);
                    that.$emit('ok');
                }
                else {
                    console.log(res.message);
                    that.$message.success(res.message);
                    that.sheetOptions = res.result;
                    that.handleModalVisible(true);
                }
            } else {
                that.$message.warning(res.message);
            }
        }).finally(() => {
        })
      },
      saveUploadInfo(){
        var that = this;
        let formData = {};
        formData.dbpath = this.fileName;
        formData.num = this.sheetNum;
        this.uploading = true;
        console.log(formData);
        postAction(this.saveAction, formData).then((res) => {
            if (res.success) {
                console.log(res.message);
                that.$message.success(res.message);
                that.handleModalVisible(false);
                var result = res.result;
                var header = JSON.parse(res.message);
                that.columns = [];
                header.forEach(function (option) {
                  if(option.field != null && option.field != ""){
                    var col = {
                      title: option.key,
                      dataIndex: option.field,
                    };
                    that.columns.push(col);
                  }
                });
                that.dataSource = result;
                that.$emit('ok');
            } else {
                that.$message.warning(res.message);
            }
        }).finally(() => {
        })
      }
    }
  }
</script>